package com.ysm.smfu.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.ysm.smfu.R;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;
import com.hyphenate.EMCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.DemoHelper;

/**
 * Created by Administrator on 2016/11/15.
 */
public class MySettingActivity extends BaseActivity {
    @BindView(R.id.title_body)
    TextView titleBody;
    @BindView(R.id.mainActivity_topbar_img)
    ImageView mainActivityTopbarImg;
    @BindView(R.id.fragment_my_quit)
    Button fragment_my_quit;
    private String name;
    private SharedPreferences currShared;
    private String userId;
    private SharedPreferences sp;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_setting);
        ButterKnife.bind(this);
        getConfigAndSet();
        titleBody.setText("设置");
        mainActivityTopbarImg.setVisibility(View.GONE);
    }

    //获取配置并且设置
    private void getConfigAndSet() {
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        name = sp.getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        userId = currShared.getString(SpKey.USERID, "");
    }

    @OnClick({R.id.fragment_my_pay_psd_Set, R.id.fragment_my_login_psd_set, R.id.fragment_my_quit})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.fragment_my_pay_psd_Set:
//                支付密码设置
                checkZhiFuPsdState();
                break;

            case R.id.fragment_my_login_psd_set:
//                修改登录密码
                UIUtils.startActivity(My_XiuGai_Activity.class, "position", 5);
                break;
            case R.id.fragment_my_quit:
//                退出登录
                showQitDialog();
                break;
        }
    }

    /**
     * 弹出退出应用对话框
     */
    private void showQitDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("确定退出数贸服务APP吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DemoHelper.getInstance().logout(false, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        StoreInfo.getInstance().clearInfo(sp, currShared);
                                        clearCookieSession();
                                        startActivity(new Intent(MySettingActivity.this, All_LoginActivity.class));
                                        finish();
//                                        友盟统计用户退出
                                        MobclickAgent.onProfileSignOff();
                                    }
                                });
                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }

                            @Override
                            public void onError(int code, String message) {
                                Looper.prepare();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showErrToast();
                                    }
                                });
                                Looper.loop();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null)
                .create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 清除cookie和session
     */
    private void clearCookieSession() {
        CookieManager.getInstance().removeSessionCookie();
    }

    /**
     * 检测支付密码状态
     * 请求地址 : app/user/getPay
     * 参数 :
     * id: 用户id   sign：签名 payPwd:支付密码
     * nonce：随机数  timestamp：时间戳
     * 签名字段 :
     * Id;nonce;timestamp外加key 秘钥
     * 返回结果	 :
     * State : 1  验证手机号;设置密码
     * State : 0  设置密码
     */

    private void checkZhiFuPsdState() {
        BaseProtocal.builder(true).checkZhiFuPsdState(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("检测支付密码" ,response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String state = jsonObject.optString("state");
                    if (TextUtils.equals(state, "1")) {
                        //设置过密码
                        Intent intent = new Intent(MySettingActivity.this, Registe_checkActivity.class);
                        intent.putExtra(SpKey.INTENT, "zhifupsd");
                        startActivityForResult(intent, 100);
                    } else if (TextUtils.equals(state, "0")) {
                        //没有设置过密码
                        UIUtils.startActivity(My_XiuGai_Activity.class, "position", 10);
                    }
                } catch (JSONException e) {

                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast(getString(R.string.netError));
            }
        }, userId);
    }
}
